<?php

namespace Acesso\Model\Business;

use Acesso\Model\AbstractTable\Usuario as LoginTable;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Zend\Db\Adapter\Adapter;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable;

class Usuario
{

    protected $_adapter;

    public function __construct( Adapter $adapter )
    {
        $this->_adapter = $adapter;

    }

    public function autentica( $usuario, $senha )
    {
        $authAdapter = new DbTable( $this->_adapter, 'usuario', 'login', 'senha' );
        $authAdapter->setCredentialTreatment( 'md5(?)' );
        $authAdapter->setIdentity( $usuario );
        $authAdapter->setCredential( $senha );
        $authService = new AuthenticationService();
        $result      = $authService->authenticate( $authAdapter );
        if ($result->isValid()) {
            $storage = $authService->getStorage();
            $storage->write( array('login' => $usuario) );
        } else {
            switch ($result->getCode()) {
                case Result::FAILURE_IDENTITY_NOT_FOUND:
                    throw new \Acesso\Exception( 'Usuário não encontrado' );
                    break;
                case Result::FAILURE_CREDENTIAL_INVALID:
                    throw new \Acesso\Exception( 'Senha incorreta' );
                    break;
                default :
                    throw new \Acesso\Exception( 'Erro desconhecido' );
                    break;
            }
        }
        $user   = new LoginTable( $this->_adapter );
        $data   = array("login = ?" => $usuario, "senha = ?" => md5( $senha ));
        $result = $user->fetchRow( $data );
        $acl    = new Acl();
        $acl->addRole( new Role( 'admin' ) )
                ->addRole( new Role( 'guest' ) );

        $acl->addResource( new Resource( '/admin/usuario/novo' ) );
        $acl->deny( 'guest', '/admin/usuario/novo' );
        $acl->deny( 'admin', '/admin/usuario/novo' );

    }

}
